<?php
namespace Twoir\Service;

/**
 * 模型调用入口
 *
 * cighsen02 365182575
 * time: 2022.12.20
 * update: 2024.05.03
*/
class BaseInfo
{
	//当前操作的表
	protected $tablename;

	//父栏目id
	protected $bclassid;

	//当前栏目id
	protected $classid;
	/**
	 * 栏目id
	 *
	 * @param string|int $classid
	 */
	public function __construct($classid = null)
	{
		$this->initialize($classid);
	}

	/**
	 * 重设置classid
	 *
	 * @param int $classid
	 * @return static
	*/
	public function setClassId($classid)
	{
		// 如果与旧相同，跳过
		if ($classid && $classid !== $this->classid) {
			// 重置
			$this->tablename 	= null;
			$this->bclassid 	= null;

			$this->initialize($classid);
		}

		return $this;
	}

    /**
     * 重设置tablename
     *
     * @param string $tablename
     * @return static
    */
    public function setTableName($tablename)
    {
    	// 如果与旧相同，跳过
    	if ($tablename && $tablename !== $this->tablename) {
    		// 重置
    		$this->tablename 	= null;
    		$this->bclassid 	= null;

    		$this->initialize($tablename);
    	}

    	return $this;
    }

	/**
	 * 返回查询条件
	 *
	 * @param int $classid
	 * @return array
	*/
	public function getWhere($classid)
	{
	    global $class_r;

	    //顶级栏目
	    if(($classid && !\is_numeric($classid)) || 0 === $this->bclassid) return [];

	    //非终级栏目
	    if($classid && isset($class_r[$classid]['islast'], $class_r[$classid]['islist']) && 0 === $class_r[$classid]['islast'] && 1 === $class_r[$classid]['islist']) {

	        $str = $class_r[$classid]['sonclass'] ? trim($class_r[$classid]['sonclass'], '|') : $classid;

	        return false !== strstr($str, '|') ? ['classid in' => explode('|', $str)] : ['classid' => $classid];
	    }

	    //终级栏目
	    return ['classid' => $classid];
	}

	/**
	 * 统计
	 *
	 * @param array $where
	 * @param array $field
	 * @param int $type
	 * @return int|throw
	 */
	public function getCount($where, $field = '', $type = '')
	{
		if (empty($this->tablename)) throw new \Exception('请先建立模型，再操作', 9200);

		return forward_static_call_array(['Twoir\System\Model\\' . $this->tablename, __FUNCTION__], [$where, $field, $type]);
	}

	/**
	 * 单条信息
	 *
	 * @param array $where 条件
	 * @param array $field 要取的字段名
	 * @param string $type [list|one]
	 * @param int $classid
	 * @return array|throw
	*/
	public function getOne($where, $field = ['*'], $groupby = '', $orderby = '', $type = '')
	{
		if (empty($this->tablename)) throw new \Exception('请先建立模型，再操作', 9200);

		return forward_static_call_array(['Twoir\System\Model\\' . $this->tablename, __FUNCTION__], [$where, $field, $groupby, $orderby, $type]);
	}

	/**
	 * 多条信息
	 *
	 * @param int $classid
	 * @param array $where 条件
	 * @param array $field 要取的字段名
	 * @param string $type [list|one]
	 * @return array|throw
	*/
	public function getList($where, $field = ['*'], $groupby = '', $orderby = '', $limit = 0, $pagesize = 10, $page = 0, $type = '')
	{
		if (empty($this->tablename)) throw new \Exception('请先建立模型，再操作', 9200);

		return forward_static_call_array(['Twoir\System\Model\\' . $this->tablename, __FUNCTION__], [$where, $field, $groupby, $orderby, $limit, $pagesize, $page, $type]);
	}

	/**
	 * 更新数据
	 *
	 * @param array $where
	 * @param array $add
	 * @param int $limit
	 * @param string $type
	 * @return bool|throw
	 */
	public function update($where = [], $add = [], $limit = null, $type = '')
	{
		if (empty($this->tablename)) throw new \Exception('请先建立模型，再操作', 9200);

		return forward_static_call_array(['Twoir\System\Model\\' . $this->tablename, __FUNCTION__], [$where, $add, $limit, $type]);
	}

	/**
	 * 删除数据
	 *
	 * @param array $where
	 * @param int $limit
	 * @param string  $orderby
	 * @param string $type
	 * @return bool|throw
	*/
	public static function delete($where = [], $limit = null, $orderby = '', $type = '')
	{
		if (empty($this->tablename)) throw new \Exception('请先建立模型，再操作', 9200);

		return forward_static_call_array(['Twoir\System\Model\\' . $this->tablename, __FUNCTION__], [$where, $limit = null, $orderby = '', $type = '']);
	}

	/**
	 * 格式化数据
	 *
	 * @param array $data
	 * @return array
	*/
	protected function format($data)
	{
		if (empty($data)) return [];

		array_walk_recursive($data, function (&$value, $key) {
			//时间
			if (in_array($key, ['newstime', 'truetime', 'lastdotime'])) {
				//Y-m-d H:i:s
				$value = date('Y-m-d', $value);
			}
			else if (is_numeric($value)) {
				//转int
				$value = (int)$value;
			}
			// 转义
			else if (in_array($key, ['smalltext', 'newstext', 'title', 'username'])) {

				$value = ehtmlspecialchars($value);
			}
		});

		return $data;
	}

	/**
	 * 初始化
	 *
	 * @param string|int $classid
	*/
	protected function initialize($classid = null)
	{
        global $class_r, $public_r;

        if ($classid && !\is_numeric($classid)) {

            $this->tablename = $this->getMethod($classid);
        }
        else {

            if ($classid && isset($class_r[$classid]['tbname']) && $class_r[$classid]['tbname']) {

                $this->tablename    = $this->getMethod($class_r[$classid]['tbname']);
                $this->bclassid     = isset($class_r[$classid]['bclassid']) ? $class_r[$classid]['bclassid'] : null;
            }

            $this->classid = $classid;
        }
	}

	/**
	 * 确定方法简短名称
	 *
	 * @param string $method 调用方法
	 * @return string 返回实际方法名
	*/
	private function getMethod($method)
	{
		foreach (array_filter(scandir(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'System' . DIRECTORY_SEPARATOR . 'Model'), function($item) { return '.' !== $item && '..' !== $item;}) as $item) {

			$item = basename($item, '.php');
			if ($method === strtolower($item)) return $item;
		}

		return null;
	}
}
